import asyncio
import random

import pygame
from pygame import K_a, K_LEFT, K_d, K_RIGHT

import cfg
from collect_gold.god import God
from collect_gold.gold import Gold
from debug import debug
from units.uiUtil import Button, drawText, gameBgImg

imgGod = pygame.image.load('assets/image/god.png')
bg = pygame.image.load('collect_gold/myGameBg.jpg')
imgGold = pygame.image.load('assets/image/gold.png')
imgGold1 = pygame.image.load('assets/image/gold1.png')
musicGold = pygame.mixer.Sound('assets/music/gold.mp3')
class GoldCollector:
    def __init__(self, dims, FPS = 60):
        self.dims = dims
        self.FPS = FPS
        # 记录时间
        self.start_time = pygame.time.get_ticks()
        # 游戏运行控制变量（gamen_running）
        self.game_running = True

        self.goldSpritesGroup = pygame.sprite.Group()  # 精灵组
    generateGoldCount = 0  # 金币数量
    generateGoldFrequency = random.randint(5, 10)  # 一次生成数量
    score = 0  # 得分

    def playMyBgMusic(self):
        pygame.mixer.music.load('assets/music/bg2.mp3')
        pygame.mixer.music.play(-1)

    '''结束界面'''

    def endInterface(self, screen, score):
        if not self.game_running:
            # 显示得分
            drawText(f'最终得金币{score}', "black", (250, 300), screen)

            # 画一个按钮，从新开始
            button_1 = Button(screen, (250, 500), '重新开始')

            # 画一个按钮，返回主菜单
            button_2 = Button(screen, (250, 700), '返回主菜单')

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    # sys.exit()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if button_1.collidepoint(pygame.mouse.get_pos()):
                        self.start_time = pygame.time.get_ticks()
                        self.score = 0
                        self.game_running = True
                    if button_2.collidepoint(pygame.mouse.get_pos()):
                        self.start_time = pygame.time.get_ticks()
                        self.score = 0
                        self.goldSpritesGroup = pygame.sprite.Group()
                        self.game_running = True
                        cfg.inGame = False

    # 游戏主循环所在函数需要由 async 定义
    async def start(self):
        # 初始化游戏界面（screen）：尺寸、背景色等
        screen = pygame.display.set_mode(self.dims)
        # 显示游戏名称
        pygame.display.set_caption("聚宝盆")
        # 初始化游戏时钟（clock），由于控制游戏帧率
        clock = pygame.time.Clock()
        # 播放背景音乐
        self.playMyBgMusic()
        # 初始化财神
        god = God(self.dims, (300, 300), imgGod)

        # 游戏主循环
        while cfg.inGame:
            # 按照给定的 FPS 刷新游戏
            # clock.tick() 函数返回上一次调用该函数后经历的时间，单位为毫秒 ms
            # dt 记录上一帧接受之后经历的时间，单位为秒 m
            # 使用 dt 控制物体运动可以使游戏物理过程与帧率无关
            dt = clock.tick(self.FPS) / 1000.0
            # 使用 asyncio 同步
            # 此外游戏主体代码中不需要再考虑 asyncio
            await asyncio.sleep(0)

            # 游戏事件处理
            # 包括键盘、鼠标输入等
            for event in pygame.event.get():
                # 点击关闭窗口按钮或关闭网页
                if event.type == pygame.QUIT:
                    pygame.quit()
                # 当 game_running 为 False 时，

            # 以背景色覆盖刷新游戏界面
            gameBgImg(screen, bg, 0, self.dims)

            # 调用 debug 函数在游戏界面左上角显示游戏帧率
            debug(f"{clock.get_fps():.1f}", color='green')

            # 给游戏定时结束
            elapsed_time = pygame.time.get_ticks() - self.start_time
            if elapsed_time > 20000:
                self.game_running = False
                self.endInterface(screen, self.score)
            else:
                drawText(f'时间：{elapsed_time}',"black",(350, 100), screen)
                # 显示文字
                drawText(f'金币：{self.score}', "black", (150, 100), screen)

            # 清空所有红包
            if not self.game_running:
                self.goldSpritesGroup = pygame.sprite.Group()

            if self.game_running:
                # 键盘事件
                key_pressed = pygame.key.get_pressed()
                if key_pressed[K_a] or key_pressed[K_LEFT]:
                    god.move("left")
                elif key_pressed[K_d] or key_pressed[K_RIGHT]:
                    god.move("right")

                # 随机生成金币
                self.generateGoldCount += 1
                if self.generateGoldCount > self.generateGoldFrequency:
                    self.generateGoldFrequency = random.randint(5, 10)
                    self.generateGoldCount = 0
                    temp = random.randint(1, 10);
                    if temp < 7:
                        gold = Gold(self.dims, (50, 50), imgGold, 10)
                        self.goldSpritesGroup.add(gold)
                    else:
                        gold1 = Gold(self.dims, (100, 100), imgGold1, 20)
                        self.goldSpritesGroup.add(gold1)

                # 更新金币
                for gold in self.goldSpritesGroup:
                    if gold.update():
                        self.goldSpritesGroup.remove(gold)

                # 碰撞检测
                for gold in self.goldSpritesGroup:
                    if self.dims[1] - gold.rect.y > 350 and pygame.sprite.collide_rect(gold, god):
                        musicGold.play()
                        self.goldSpritesGroup.remove(gold)
                        self.score += gold.score
                # 画金币
                self.goldSpritesGroup.draw(screen)

                # 画财神
                god.draw(screen)

            # 将游戏界面内容输出至屏幕
            pygame.display.update()

        # 跳出游戏主循环，退出游戏
        cfg.inGame = False

